package router

import (
	"ccGame/controller"
	"github.com/buaazp/fasthttprouter"
	"github.com/valyala/fasthttp"
	//"net/http"
	"ccGame/common"
	"github.com/Sirupsen/logrus"
)


func BaseHandler(r fasthttp.RequestHandler, auth bool) fasthttp.RequestHandler {

	return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx){
		ctx.Response.Header.Add("Access-Control-Allow-Origin","*")
		ctx.Response.Header.Add("Access-Control-Allow-Headers","Access-control-allow-headers,Access-control-allow-methods,Access-control-allow-origin,Authorization,authorization,Content-Type,X-Requested-With")
		ctx.Response.Header.Add("Access-Control-Allow-Methods","GET,POST,OPTIONS,HEAD,PUT")
		ctx.Response.Header.Add("Access-Control-Allow-Credentials","true")


		// 捕获并拦截程序的异常
		defer func() {
			//if err:= recover(); err != nil {
			//	ctx.SetStatusCode(http.StatusInternalServerError) // 500
			//	//SendMsg(ctx,false,ECM(Message_ArgumentIsMissing)) // 服务器异常 提示： 缺少参数
			//
			//}
			//return
		}()
		// 对用户合法性 进行校验
		if auth {
			//var user = common.UserInfo{
			//	ID:5,
			//	Username:"eretret",
			//}
			//token , err := common.CreateToken(&user)
			//if err != nil{
			//	logrus.Error(err)
			//
			//}
			token := ctx.Request.Header.Peek("Authorization")

			_ ,newToken ,err := common.ParseToken(string(token))
			if err != nil {
				logrus.Error(err)
				common.SendMsg(ctx,401,"请登录---")
				return
			}
			if newToken != ""{
				ctx.Response.Header.Add("Authorization",newToken)
			}
			//fmt.Println(userinfo)

			 r(ctx)
		}else{
			 r(ctx)
		}

	})

}
func OptionsRequestCors(ctx *fasthttp.RequestCtx){
	//origin := ctx.Request.Header.Peek("Origin")
	//ctx.Response.Header.Add("Access-Control-Allow-Origin",string(origin))
	ctx.Response.Header.Add("Access-Control-Allow-Origin","*")
	ctx.Response.Header.Add("Access-Control-Allow-Headers","Access-control-allow-headers,Access-control-allow-methods,Access-control-allow-origin,Authorization,authorization,Content-Type,X-Requested-With")
	ctx.Response.Header.Add("Access-Control-Allow-Methods","GET,POST,OPTIONS,HEAD,PUT")
	ctx.Response.Header.Add("Access-Control-Allow-Credentials","true")
	ctx.SetStatusCode(204)
	ctx.Write([]byte{12,23,42})

}

var router *fasthttprouter.Router


func RouterManager() *fasthttprouter.Router{
	router = fasthttprouter.New()
	router.OPTIONS("/user",OptionsRequestCors)
	router.POST("/user",  BaseHandler(controller.LoginAction,false))



	return router
}

